import { harTasks, OhosPluginId, OhosHarContext } from '@ohos/hvigor-ohos-plugin';
import { getNode, HvigorNode, HvigorTask, hvigor } from '@ohos/hvigor'
import fs from 'fs';

export default {
    system: harTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
    plugins:[]         /* Custom plugin to extend the functionality of Hvigor. */
}

interface OhPackage {
    name: string,
    version: string
}
// 获取当前hvigorNode节点对象
const node: HvigorNode = getNode(__filename);
hvigor.buildFinished(() => {
    // 构建结束后，重命名har，将taoyao.har重命名为带有版本号的文件名
    // 例如，桃夭的版本为是1.0.8，taoyao.har重命名为taoyao_1.0.8.har
    const harContext = node.getContext(OhosPluginId.OHOS_HAR_PLUGIN) as OhosHarContext
    const moduleName = harContext.getModuleName()
    const modulePath = harContext.getModulePath()
    const ohPackagePath = modulePath + '/oh-package.json5'
    const content = fs.readFileSync(ohPackagePath, 'utf-8')
    const ohPackage: OhPackage = JSON.parse(content)
    const originFilePath = `${modulePath}/build/default/outputs/default/${moduleName}.har`
    const targetFilePath = `${modulePath}/build/default/outputs/default/${moduleName}_${ohPackage.version}.har`
    if (fs.existsSync(originFilePath)) {
        fs.rename(originFilePath, targetFilePath, (err) => {
            throw new Error(`重命名发生错误：${err?.message}`)
        })
    }
})